using AutoMapper;
using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    /// <summary>
    /// 保存工艺路线处理器（主表+子表一起保存）
    /// </summary>
    public class SaveRouteHandler : IRequestHandler<SaveRouteCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepo;
        private readonly IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> _processRepo;
        private readonly IMapper _mapper;

        public SaveRouteHandler(
            IBaseRepository<RouteModel> routeRepo,
            IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> processRepo,
            IMapper mapper)
        {
            _routeRepo = routeRepo;
            _processRepo = processRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(SaveRouteCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            try
            {
                RouteModel routeModel;
                bool isAdd = request.Id == 0;

                // 验证工艺路线编号是否重复
                var existingRoute = _routeRepo.GetAll()
                    .Where(x => x.Code == request.Code && x.Id != request.Id)
                    .ToList().FirstOrDefault();
                if (existingRoute != null)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "工艺路线编号已存在";
                    return res;
                }

                if (isAdd)
                {
                    // 新增工艺路线
                    routeModel = new RouteModel
                    {
                        Code = request.Code,
                        Name = request.Name,
                        Approved = request.EnableApproval ? (byte)1 : (byte)0,
                        Remark = request.Remark,
                        CreateBy = request.OperateBy,
                        CreateTime = DateTime.Now,
                        UpdateBy = request.OperateBy,
                        UpdateTime = DateTime.Now
                    };

                    await _routeRepo.CreateAsync(routeModel);

                    // 再次查询以获取数据库生成的主键
                    var inserted = _routeRepo.GetAll()
                        .Where(x => x.Code == request.Code)
                        .ToList().FirstOrDefault();
                    if (inserted != null)
                    {
                        routeModel.Id = inserted.Id;
                    }
                }
                else
                {
                    // 编辑工艺路线
                    routeModel = _routeRepo.GetAll()
                        .Where(x => x.Id == request.Id)
                        .ToList().FirstOrDefault();

                    if (routeModel == null)
                    {
                        res.Code = ApiEnum.Fail;
                        res.Msg = "工艺路线不存在";
                        return res;
                    }

                    routeModel.Code = request.Code;
                    routeModel.Name = request.Name;
                    routeModel.Approved = request.EnableApproval ? (byte)1 : (byte)0;
                    routeModel.Remark = request.Remark;
                    routeModel.UpdateBy = request.OperateBy;
                    routeModel.UpdateTime = DateTime.Now;

                    await _routeRepo.UpdateAsync(routeModel);
                }

                // 处理工序列表
                await SaveProcesses(routeModel.Id, request.Steps, request.OperateBy);

                res.Data = routeModel.Id;
                res.Code = ApiEnum.Success;
                res.Msg = isAdd ? "新增工艺路线成功" : "编辑工艺路线成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"保存工艺路线失败：{ex.Message}";
            }

            return res;
        }

        /// <summary>
        /// 生成长整型ID
        /// </summary>
        /// <returns>长整型ID</returns>
        private long GenerateId()
        {
            // 基于时间戳生成ID（毫秒时间戳 + 3位随机数）
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var random = new Random().Next(100, 999);
            return timestamp * 1000 + random;
        }

        /// <summary>
        /// 保存工序列表
        /// </summary>
        /// <param name="routeId">工艺路线ID</param>
        /// <param name="steps">工序列表</param>
        /// <param name="operateBy">操作人</param>
        private async System.Threading.Tasks.Task SaveProcesses(int routeId, List<SaveRouteStepCommand> steps, string operateBy)
        {
            // 获取现有工序
            var existingProcesses = _processRepo.GetAll()
                .Where(x => x.RoutdId == routeId)
                .ToList();

            // 处理删除的工序
            var deletedSteps = steps.Where(x => x.IsDeleted && x.Id > 0).ToList();
            foreach (var deletedStep in deletedSteps)
            {
                var processToDelete = existingProcesses.FirstOrDefault(x => x.Id == deletedStep.Id);
                if (processToDelete != null)
                {
                    await _processRepo.DeleteAsync(processToDelete.Id);
                }
            }

            // 处理新增和编辑的工序
            var activeSteps = steps.Where(x => !x.IsDeleted).ToList();
            foreach (var stepCommand in activeSteps)
            {
                if (stepCommand.Id == 0)
                {
                    // 新增工序
                    var newProcess = new B.S.XZYData.Domain.ZSHH.Process
                    {
                        Id = GenerateId(), // 生成long类型ID
                        ProcessNumber = stepCommand.ProcessCode,
                        RoutdId = routeId,
                        ProcessName = stepCommand.ProcessName,
                        ReportingRatio = (int?)stepCommand.Ratio,
                        ReportingPermissions = stepCommand.ReportingPermissions,
                        DefectiveItemList = stepCommand.DefectiveItemList,
                        TestField1 = stepCommand.TestField1,
                        TestField2 = stepCommand.TestField2,
                        Creator = operateBy,
                        CreatorDate = DateTime.Now,
                        Updator = operateBy,
                        UpdatorDate = DateTime.Now
                    };

                    await _processRepo.CreateAsync(newProcess);
                }
                else
                {
                    // 编辑工序
                    var existingProcess = existingProcesses.FirstOrDefault(x => x.Id == stepCommand.Id);
                    if (existingProcess != null)
                    {
                        existingProcess.ProcessNumber = stepCommand.ProcessCode;
                        existingProcess.ProcessName = stepCommand.ProcessName;
                        existingProcess.ReportingRatio = (int?)stepCommand.Ratio;
                        existingProcess.ReportingPermissions = stepCommand.ReportingPermissions;
                        existingProcess.DefectiveItemList = stepCommand.DefectiveItemList;
                        existingProcess.TestField1 = stepCommand.TestField1;
                        existingProcess.TestField2 = stepCommand.TestField2;
                        existingProcess.Updator = operateBy;
                        existingProcess.UpdatorDate = DateTime.Now;

                        await _processRepo.UpdateAsync(existingProcess);
                    }
                }
            }
        }
    }
} 